import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import QtQuick.Shapes 1.15

// 料罐监控主界面内容
MainView {
    id: root
    width: 800
    height: 480

    signal reloadPageRequested

    // 全局设置
    property int lowLevelThreshold : mymodbus.lowLevelThreshold // 低料位阈值，单位：百分比
    property int totalSilos : mymodbus.totalSilos       // 总料罐数量
    property int currentPage: 0         // 当前页面索引
    property int ifshowTotal : mymodbus.ifshowTotal        // 是否显示合计
    property int itemsPerPage : mymodbus.itemsPerPage       // 每页显示的料罐数量
    property int totalPages: ifshowTotal?Math.ceil((totalSilos - (itemsPerPage - 1)) / itemsPerPage) + 1 : Math.ceil(totalSilos / itemsPerPage)  // 总页数
    property string lastUpdateTime: ""
    property int commStatus: mymodbus.commStatus       // 通讯状态
    property int counttime: 0
    property int btnHeight: 50

    // 从mymodbus获取料罐ID列表并初始化数据源
    property var silosData : initSilosData()

    Component.onCompleted: {
        updateData();
        updateTimer.start()
        // 连接信号到reloadPage函数
        reloadPageRequested.connect(reloadPage);
        
        // 连接mymodbus的刷新信号到本组件的信号
        if (mymodbus && mymodbus.hasOwnProperty("refreshPageSignal")) {
            mymodbus.refreshPageSignal.connect(reloadPage);
        }
    }
    Component.onDestruction: {
       updateTimer.destroy()
       autoPageTimer.destroy()
    }

    function getitemsperpage(){
        var lst=[];
        lst.push(1);
        lst.push(4);
        return lst
    }

    function getshowtotal(){
        var lst=[];
        lst.push("否");
        lst.push("是");
        return lst
    }

    function getperpageshowtime(){
        var lst=[];
        lst.push(0);
        lst.push(10);
        lst.push(20);
        lst.push(30);
        lst.push(40);
        lst.push(50);
        lst.push(60);
        return lst
    }

    // 添加初始化函数
    function initSilosData() {
        var result = [];
        //console.log("mymodbus.lowLevelThreshold:"+lowLevelThreshold);
        //console.log("mymodbus.totalSilos:"+totalSilos);
        //console.log("mymodbus.ifshowTotal:"+ifshowTotal);
        //console.log("mymodbus.itemsPerPage:"+itemsPerPage);
        //console.log("mymodbus.silosIDList:"+mymodbus.silosIDList);
        //console.log("mymodbus.silosCapacityList:"+mymodbus.silosCapacityList);
        var lst1 = mymodbus.silosIDList;
        var idList = lst1.split("|");

        var lst2 = mymodbus.silosCapacityList;
        var capList = lst2.split("|");

        var lst3 = mymodbus.silosName;
        var nameList = lst3.split("|");

        // 第一项为合计
        if(mymodbus.ifshowTotal) {
            result.push({id: "合计", weight: 0, capacity: 0, isLowLevel: false ,isNoData: false,name: "合计"});
        }
        
        //console.log("idList.length:"+idList.length);
        //console.log("capList.length:"+capList.length);

        for(var i = 0; i < idList.length; i++) {
            var id = parseInt(idList[i]);
            //console.log("id["+i+"]:"+id);
            var capacity = parseInt(capList[i])/1000;
            //console.log("capacity["+i+"]:"+capacity);
            if(!isNaN(id) && !isNaN(capacity)) {
                //console.log("result.push({id: "+id+", weight: 0, capacity: "+capacity+", isLowLevel: false});");
                result.push({id: id, weight: 0, capacity: capacity, isLowLevel: false ,isNoData: false,name: nameList[i]});
            }
        }
        return result;
    }

    // 定时器 - 用于更新数据和自动翻页
    Timer {
        id: updateTimer
        interval: 1000 // 1秒更新一次数据
        running: false
        repeat: true
        onTriggered: {
            updateData();
            if(counttime <= 60)
            {
                counttime++;
            }
        }
    }

    // 自动翻页定时器
    Timer {
        id: autoPageTimer
        interval: mymodbus.perPageShowtime*1000 // 从mymodbus获取自动翻页时间间隔
        running: mymodbus.perPageShowtime===0?false:true
        repeat: true
        onTriggered: {
            if (currentPage < totalPages - 1) {
                currentPage++;
                silosView.positionViewAtIndex(currentPage, ListView.Beginning);
            } else {
                currentPage = 0;
                silosView.positionViewAtIndex(0, ListView.Beginning);
            }
        }
    }

    //重新加载页面函数
    function reloadPage(){
        totalSilos = mymodbus.totalSilos       // 总料罐数量
        currentPage = 0         // 当前页面索引
        totalPages = ifshowTotal?Math.ceil((totalSilos - (itemsPerPage - 1)) / itemsPerPage) + 1 : Math.ceil(totalSilos / itemsPerPage)
        silosData = initSilosData();
    }

    // 更新数据函数
    function updateData() {
        commStatus = mymodbus.commStatus;
        var lst3 = mymodbus.silosWeightList;
        //console.log("updateData:lst3:"+lst3);
        var weightList = lst3.split("|");
        var lst4 = mymodbus.silosUpdateTimeList;
        var updateTimeList = lst4.split("|");
        //console.log("updateData:weightList.length:"+weightList.length);
        //for(var j = 0; j < weightList.length; j++)
        //{
        //    console.log("updateData:weightList["+j+"]:"+weightList[j]);
        //}

        // 从索引1开始（跳过合计项）
        var startIndex = mymodbus.ifshowTotal ? 1 : 0;
        for (var i = startIndex; i < silosData.length; i++) {
            var weightindex = mymodbus.ifshowTotal ? i - 1 : i;
            //console.log("updateData:i:"+weightindex+",weightList[i]:"+weightList[weightindex]);
            var weight = parseInt(weightList[weightindex]);
            //console.log("updateData:i:"+weightindex+",weight:"+weight);
            if (!isNaN(weight)) {
                silosData[i].weight = Math.round((weight/1000) * 10) / 10;
            }
            //console.log("updateData:silosData[i].weight:"+silosData[i].weight);
            // 更新低料位状态
            var percentage = (silosData[i].weight / silosData[i].capacity) * 100;
            //console.log("updateData:percentage:"+percentage);
            silosData[i].isLowLevel = percentage < lowLevelThreshold;
            if(counttime>=60)
            {
                silosData[i].isNoData = parseInt(updateTimeList[weightindex])===1?true:false;
            }
            //console.log("updateData:silosData[i].isLowLevel:"+silosData[i].isLowLevel);
        }

        if(ifshowTotal)
        {
            // 更新合计数据
            var totalWeight = 0;
            var totalCapacity = 0;
            for (var j = 1; j < silosData.length; j++) {
                totalWeight += silosData[j].weight;
                totalCapacity += silosData[j].capacity;
            }
            var totalPercentage = (totalWeight / totalCapacity) * 100;
            silosData[0].weight = Math.round(totalWeight * 10) / 10;
            silosData[0].capacity = totalCapacity;
            silosData[0].isLowLevel = totalPercentage < lowLevelThreshold;
        }

        // 更新最后更新时间
        lastUpdateTime = Qt.formatDateTime(new Date(), "yyyy-MM-dd hh:mm:ss");

        //var tempData = silosData;
        //silosData = [];
        //for (var k = 0; k < tempData.length; k++) {
        //    silosData.push(tempData[k]);
        //}

        // 刷新ListView来显示最新数据
        silosView.model = 0;
        silosView.model = totalPages;
        if(currentPage >= totalPages)
        {
           currentPage = 0; 
        }
        silosView.positionViewAtIndex(currentPage, ListView.Beginning);
    }

    // 顶部栏
    Item {
        id: topBar
        width: parent.width
        height: 29

        Rectangle {
            id: titleBar
            anchors.fill: parent
            color: "#40A0A0"  // 蓝色标题栏

            Text {
                id: systemTitle
                text: qsTr("料罐监测系统")
                color: "white"
                font.pixelSize: 16
                font.bold: true  // 加粗字体
                anchors.verticalCenter: parent.verticalCenter
                anchors.left: parent.left
                anchors.leftMargin: 10
            }

            Text {
                id: dateTimeDisplay
                text: Qt.formatDateTime(new Date(), "yyyy-MM-dd hh:mm:ss")
                color: "white"
                font.pixelSize: 14
                anchors.verticalCenter: parent.verticalCenter
                anchors.right: parent.right
                anchors.rightMargin: 10
            }
        }

        // 定时器更新时间
        Timer {
            interval: 1000
            running: true
            repeat: true
            onTriggered: {
                dateTimeDisplay.text = Qt.formatDateTime(new Date(), "yyyy-MM-dd hh:mm:ss");
            }
        }
    }

    // 中部数据显示区域
    ListView {
        id: silosView
        width: parent.width
        height: root.height - topBar.height - bottomBar.height
        anchors.top: topBar.bottom
        orientation: ListView.Horizontal
        snapMode: ListView.SnapOneItem
        flickDeceleration: 100
        interactive: false //禁止滑动

        model: totalPages
        delegate: pageDelegate
    
        Component {
            id: pageDelegate
            Item {
                property int pageIndex: index
                width: silosView.width
                height: silosView.height

                // 根据页面索引显示不同的料罐
                GridLayout {
                    id: silosGrid
                    anchors.fill: parent
                    columns: 2
                    rows: 2
                    rowSpacing: 5
                    columnSpacing: 5
                    anchors.margins: 5

                    // 使用Repeater动态生成卡片
                    Repeater {
                        model: itemsPerPage
                        delegate: Loader {
                            sourceComponent: siloCard
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            onLoaded: {
                                // 根据页面索引和卡片索引计算对应的silo数据索引
                                var dataIndex;
                                dataIndex = itemsPerPage + (pageIndex - 1) * itemsPerPage + index;
                                if (dataIndex >= silosData.length) {
                                    // 超出范围时隐藏组件
                                    item.visible = false;
                                }
                                else
                                {
                                    item.visible = true;
                                    item.siloData = silosData[dataIndex];
                                    item.itemsPerColumnAndRow = Math.sqrt(itemsPerPage);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // 底部栏
    Item {
        id: bottomBar
        width: parent.width
        height: 36
        anchors.bottom: parent.bottom

        Rectangle {
            anchors.fill: parent
            color: "#0A3653"  // 深色底部栏

            // 通讯状态指示
            Row {
                id: statusRow
                anchors.left: parent.left
                anchors.leftMargin: 10
                anchors.verticalCenter: parent.verticalCenter
                spacing: 5 // 使用spacing控制子项间距
                visible: commStatus !== 1 // 当commStatus等于1时不显示

                Rectangle {
                    width: 16
                    height: 16
                    radius: 8
                    color: commStatus ===0 ? "#00FF00" : "#FF0000"
                    anchors.verticalCenter: parent.verticalCenter
                }

                Text {
                    text: {
                        switch(commStatus) {
                            case 0: return qsTr("通讯正常");
                            case 1: return qsTr("模块未配置");
                            case 2: return qsTr("连接中");
                            case 3: return qsTr("寻找SIM卡");
                            case 4: return qsTr("注册网络");
                            case 5: return qsTr("打开客户端");
                            case 6: return qsTr("连接服务器");
                            case 7: return qsTr("订阅主题");
                            default: return qsTr("通讯异常");
                        }
                    }
                    color: "white"
                    font.pixelSize: 16
                    anchors.verticalCenter: parent.verticalCenter
                }
            }

            // 页面指示器
            Row {
                id: pageIndicator
                anchors.horizontalCenter: parent.horizontalCenter
                anchors.verticalCenter: parent.verticalCenter
                spacing: 5

                // 上一页按钮
                Button {
                    id: prevPageButton
                    text: "<<<"
                    width: 120
                    height: 36
                    onClicked: {
                        if (currentPage > 0) {
                            currentPage--;
                            silosView.positionViewAtIndex(currentPage, ListView.Center);
                            if(mymodbus.perPageShowtime > 0)
                            {
                                autoPageTimer.restart();
                            }
                        }
                    }
                    enabled: currentPage > 0
                    background: Rectangle {
                        color: "#40A0A0"
                        radius: 5
                    }
                }

                // 使用Repeater根据总页数动态生成页面指示器
                Repeater {
                    model: totalPages
                    delegate: Rectangle {
                        width: 16
                        height: 16
                        radius: 8
                        anchors.verticalCenter: parent.verticalCenter
                        // 当前页高亮显示#40A0A0，其他页面显示#555555
                        color: index === currentPage ? "#40A0A0" : "#555555"
                        MouseArea {
                            anchors.fill: parent
                            onClicked: {
                                currentPage = index;
                                silosView.positionViewAtIndex(index, ListView.Beginning);
                            }
                        }
                    }
                }
                Button {
                    id: nextPageButton
                    text: ">>>"
                    width: 120
                    height: 36
                    onClicked: {
                        if (currentPage < totalPages - 1) {
                            currentPage++;
                            silosView.positionViewAtIndex(currentPage, ListView.Center);
                            if(mymodbus.perPageShowtime > 0)
                            {
                                autoPageTimer.restart();
                            }
                        }
                    }
                    enabled: currentPage < totalPages - 1
                    background: Rectangle {
                        color: "#40A0A0"
                        radius: 5
                    }
                }
            }

            // 参数设置按钮
            Button {
                id: settingsButton
                text: qsTr("参数设置")
                width: 150
                height: 36

                anchors.right: parent.right
                anchors.rightMargin: 10
                anchors.verticalCenter: parent.verticalCenter
                background: Rectangle {
                    color: "#40A0A0"
                    radius: 5
                }
                onClicked: {
                    // 打开参数设置对话框
                    settingsDialog.visible = true;
                    updateTimer.stop();
                }
            }
        }
    }

    // 参数设置对话框
    Dialog {
        id: settingsDialog
        title: qsTr("参数设置")
        width: 800
        height: 480
        modal: true

        ColumnLayout {
            width: parent.width
            spacing: 10
            anchors.margins: 10

            // 基本设置部分
            GroupBox {
                title: qsTr("基本设置")
                Layout.fillWidth: true
                //Layout.preferredHeight: 120

                GridLayout {
                    columns: 2
                    rows: 2
                    rowSpacing: 10
                    columnSpacing: 50
                    anchors.margins: 10

                    RowLayout {
                        Layout.row:0
                        Layout.column:0
                        Label {
                            text: qsTr("低料位阈值：")
                            width: 120
                        }
                        SpinBox {
                            id: thresholdSpinBox
                            from: 1
                            to: 50
                            value: lowLevelThreshold
                            onValueChanged: {
                            }
                        }
                        Label {
                            text: qsTr("%")
                        }
                    }
                    RowLayout {
                        Layout.row:0
                        Layout.column:1
                        Label {
                            text: qsTr("每页显示：")
                            width: 120
                        }
                        ComboBox
                        {
                            id:itemsperpage
                            Layout.preferredWidth: 80
                            Layout.preferredHeight: 50
                            model:getitemsperpage()
                            currentIndex: mymodbus.itemsPerPage===1?0:1
                        }
                        Label {
                            text: qsTr("个")
                        }
                    }
                    RowLayout {
                        Layout.row:1
                        Layout.column:0
                        Label {
                            text: qsTr("是否显示合计：")
                            width: 120
                        }
                        ComboBox
                        {
                            id:showtotal
                            Layout.preferredWidth: 80
                            Layout.preferredHeight: 50
                            model:getshowtotal()
                            currentIndex: mymodbus.ifshowTotal
                        }
                    }
                    RowLayout {
                        Layout.row:1
                        Layout.column:1
                        Label {
                            text: qsTr("自动翻页时间：")
                            width: 120
                        }
                        ComboBox
                        {
                            id:perpageshowtime
                            Layout.preferredWidth: 80
                            Layout.preferredHeight: 50
                            model:getperpageshowtime()
                            currentIndex: mymodbus.perPageShowtime/10
                        }
                        Label {
                            text: qsTr("秒")
                        }
                    }
                }
            }
            // 按钮区域
            RowLayout {
                Layout.alignment: Qt.AlignRight
                spacing: 10

                Button {
                    text: qsTr("确定")
                    onClicked: {
                        lowLevelThreshold = thresholdSpinBox.value;
                        itemsPerPage = itemsperpage.currentValue;
                        ifshowTotal = showtotal.currentIndex;
                        mymodbus.setlowLevelThreshold(lowLevelThreshold);
                        mymodbus.setItemsPerPage(itemsperpage.currentValue);
                        mymodbus.setIfshowTotal(showtotal.currentIndex);
                        mymodbus.setPerPageShowtime(perpageshowtime.currentValue);
                        if(perpageshowtime.currentValue===0)
                        {
                            autoPageTimer.stop();
                        }
                        else
                        {
                            autoPageTimer.stop();
                            autoPageTimer.interval=perpageshowtime.currentValue*1000;
                            autoPageTimer.start();
                        }
                        reloadPage();
                        updateData(); // 确保所有数据更新
                        settingsDialog.visible = false;
                        updateTimer.start();
                    }
                }

                Button {
                    text: qsTr("取消")
                    onClicked: {
                        thresholdSpinBox.value = lowLevelThreshold;
                        itemsperpage.currentIndex = mymodbus.itemsPerPage===1?0:1
                        showtotal.currentIndex = mymodbus.ifshowTotal
                        perpageshowtime.currentIndex = mymodbus.perPageShowtime/10
                        settingsDialog.visible = false;
                        updateTimer.start();
                    }
                }
            }
            RowLayout {
                Layout.fillWidth: true
                spacing: 20
                Layout.alignment: Qt.AlignCenter
                Layout.preferredHeight : btnHeight*3
                 Button {
                    text: qsTr("导出参数到U盘")
                    Layout.preferredHeight: btnHeight
                    Layout.minimumHeight: btnHeight 
                    onClicked: {
                        // 这里实现U盘导入参数的逻辑
                        var res = mymodbus.uDiskExportConfig();
                        if(res)
                        {
                            upgradeSaveOKDialog.title=qsTr("配置已导出!")
                            
                        }
                        else
                        {
                            upgradeSaveOKDialog.title=qsTr("配置导出失败!")
                        }
                        upgradeSaveOKDialog.open()
                        upgradeSaveOKDialog.accepted.connect(function() {
                                                upgradeSaveOKDialog.close();
                                                settingsDialog.visible=false;
                                                updateTimer.start();
                                            })
                    }
                }

                Button {
                    text: qsTr("U盘导入参数")
                    Layout.preferredHeight: btnHeight
                    Layout.minimumHeight: btnHeight 
                    onClicked: {
                        // 这里实现U盘导入参数的逻辑
                        var res = mymodbus.uDiskImportConfig();
                        if(res)
                        {
                            upgradeSaveOKDialog.title=qsTr("下载完成，请确认完成升级！")
                            upgradeSaveOKDialog.open()
                            upgradeSaveOKDialog.accepted.connect(function() {
                                                    //upgradeSaveOKDialog.close();
                                                    //settingsDialog.visible=false;
                                                    //updateTimer.start();
                                                    mymodbus.programRestart();
                                                })
                        }
                        else
                        {
                            upgradeSaveOKDialog.title=qsTr("下载失败，请稍后重试！")
                            upgradeSaveOKDialog.open()
                            upgradeSaveOKDialog.accepted.connect(function() {
                                                    upgradeSaveOKDialog.close()
                                                    settingsDialog.visible=false;
                                                    updateTimer.start();
                                                })
                        }
                    }
                }

                Button {
                    text: qsTr("U盘升级程序")
                    Layout.preferredHeight: btnHeight
                    Layout.minimumHeight: btnHeight 
                    onClicked: {
                        // 这里实现U盘升级程序的逻辑
                        var res = mymodbus.uDiskUpgrade();
                        if(res)
                        {
                            upgradeSaveOKDialog.title=qsTr("下载完成，请重启完成升级！")
                            upgradeSaveOKDialog.open()
                            upgradeSaveOKDialog.accepted.connect(function() {
                                                    //upgradeSaveOKDialog.close();
                                                    //settingsDialog.visible=false;
                                                    //updateTimer.start();
                                                    mymodbus.reBoot();
                                                })
                        }
                        else
                        {
                            upgradeSaveOKDialog.title=qsTr("下载失败，请稍后重试！")
                            upgradeSaveOKDialog.open()
                            upgradeSaveOKDialog.accepted.connect(function() {
                                                    upgradeSaveOKDialog.close()
                                                    settingsDialog.visible=false;
                                                    updateTimer.start();
                                                })
                        }
                    }
                }
                Button {
                    text: qsTr("设定日期时间")
                    Layout.preferredHeight: btnHeight
                    Layout.minimumHeight: btnHeight 
                    onClicked: {
                        settimedlg.open()
                        settimedlg.exec(Qt.formatDateTime(new Date(), "yyyy-MM-dd hh:mm:ss"))
                    }
                }
            }
        }
    }

    // 料罐显示卡片组件
    Component {
        id: siloCard
        Item {
            id: cardRoot
            property var siloData: ({id: 0, weight: 0, capacity: 0, isLowLevel: false ,isNoData: false,name: ""})
            property int itemsPerColumnAndRow: 2
            // 计算百分比
            property real percentage: siloData.weight / siloData.capacity * 100

            // 卡片主体
            Rectangle {
                id: cardBackground
                anchors.fill: parent
                color: "#2A2A2A"
                border.color: siloData.isNoData ? "#FF4444" : "#40A0A0"
                border.width: 8
                radius: 8

                // 闪烁动画 - 无数据时
                SequentialAnimation on border.color {
                    id: blinkAnimation
                    running: siloData.isNoData
                    loops: Animation.Infinite
                    ColorAnimation { to: "#FF4444"; duration: 500 }
                    ColorAnimation { to: "#40A0A0"; duration: 500 }
                }
            }

            GridLayout {
                id: cardLayout
                anchors.fill: parent
                columns: 2
                rows: 2
                anchors.margins: 10

                // 料罐ID
                Text {
                    text: siloData.id === "合计" ? qsTr("合计") : (siloData.name && !siloData.name.toString().trim().isEmpty ? siloData.name : qsTr("料罐") + siloData.id)
                    color: "white"
                    font.pixelSize: 80 / itemsPerColumnAndRow
                    font.bold: true
                    Layout.row: 0
                    Layout.column: 0
                    Layout.preferredWidth: 300 / itemsPerColumnAndRow
                    Layout.maximumWidth: 300 / itemsPerColumnAndRow
                    Layout.minimumWidth: 300 / itemsPerColumnAndRow
                    Layout.preferredHeight: 80 / itemsPerColumnAndRow
                    Layout.maximumHeight: 80 / itemsPerColumnAndRow
                    Layout.minimumHeight: 80 / itemsPerColumnAndRow
                    horizontalAlignment: Text.AlignLeft
                    verticalAlignment:Text.AlignTop
                }
                Item {
                    id: progressRingContainer
                    Layout.rowSpan: 2
                    Layout.columnSpan: 1
                    Layout.row: 0
                    Layout.column: 1
                    Layout.alignment: Qt.AlignLeft
                    width: 300 / itemsPerColumnAndRow
                    height: 300 / itemsPerColumnAndRow

                    property real centerX: (width / 2) + 25
                    property real centerY: height / 2
                    property real radius: 120 / itemsPerColumnAndRow // 统一的半径值
                     // 背景圆环 - 确保与进度圆环同心
                    Shape {
                        id: backgroundRing
                        anchors.fill: parent

                        ShapePath {
                            strokeWidth: 40 / itemsPerColumnAndRow
                            strokeColor: "#f5f5f5"
                            fillColor: "transparent"
                            capStyle: ShapePath.RoundCap
                            // 从圆的上顶点开始
                            startX: progressRingContainer.centerX
                            startY: progressRingContainer.centerY - progressRingContainer.radius
                            PathArc {
                                // 终点回到起点（完整圆环）
                                x: progressRingContainer.centerX + progressRingContainer.radius * Math.sin(Math.PI * 2 * 99.9 / 100)
                                y: progressRingContainer.centerY - progressRingContainer.radius * Math.cos(Math.PI * 2 * 99.9 / 100)
                                radiusX: progressRingContainer.radius
                                radiusY: progressRingContainer.radius
                                useLargeArc: true
                                direction: PathArc.Clockwise
                            }
                        }
                    }

                    // 进度圆环 - 确保与背景圆环同心，并从顶部开始
                    Shape {
                        id: progressRing
                        anchors.fill: parent

                        SequentialAnimation on opacity {
                            id: warningBlinkAnimation3
                            running: siloData.isLowLevel
                            loops: Animation.Infinite
                            NumberAnimation { to: 0.3; duration: 500 }
                            NumberAnimation { to: 1; duration: 500 }
                        }

                        ShapePath {
                            strokeWidth: 40 / itemsPerColumnAndRow
                            strokeColor: siloData.isLowLevel ? "#FF4444" : '#08e71a'
                            fillColor: "transparent"
                            capStyle: ShapePath.RoundCap
                            // 从圆的上顶点开始
                            startX: progressRingContainer.centerX
                            startY: progressRingContainer.centerY - progressRingContainer.radius
                            PathArc {
                                // 使用数学公式计算终点位置，确保从顶部开始顺时针绘制
                                x: cardRoot.percentage<0?progressRingContainer.centerX + progressRingContainer.radius * Math.sin(Math.PI * 2 * 0 / 100):cardRoot.percentage>=100?progressRingContainer.centerX + progressRingContainer.radius * Math.sin(Math.PI * 2 * 99.9 / 100):progressRingContainer.centerX + progressRingContainer.radius * Math.sin(Math.PI * 2 * cardRoot.percentage / 100)
                                y: cardRoot.percentage<0?progressRingContainer.centerY - progressRingContainer.radius * Math.cos(Math.PI * 2 * 0 / 100):cardRoot.percentage>=100?progressRingContainer.centerY - progressRingContainer.radius * Math.cos(Math.PI * 2 * 99.9 / 100):progressRingContainer.centerY - progressRingContainer.radius * Math.cos(Math.PI * 2 * cardRoot.percentage / 100)
                                radiusX: progressRingContainer.radius
                                radiusY: progressRingContainer.radius
                                useLargeArc: cardRoot.percentage > 50
                                direction: PathArc.Clockwise
                            }
                        }
                    }

                    // 百分比文字 - 精确居中
                    Text {
                        id: t
                        //text: String("%1%").arg(Math.round(cardRoot.percentage))//精确到个位
                        text: String("%1%").arg(cardRoot.percentage.toFixed(1))//精确到小数点后1位
                        color: "#f5f5f5"
                        x: progressRingContainer.centerX - width/2
                        y: progressRingContainer.centerY - height/2
                        verticalAlignment: Text.AlignVCenter
                        horizontalAlignment: Text.AlignHCenter
                        font.pixelSize: 40 / itemsPerColumnAndRow
                        font.bold: true
                        z: 10
                    }
                }

                // 重量显示
                Column {
                    Layout.row: 1
                    Layout.column: 0
                    Layout.preferredWidth: 300 / itemsPerColumnAndRow
                    Layout.maximumWidth: 300 / itemsPerColumnAndRow
                    Layout.minimumWidth: 300 / itemsPerColumnAndRow
                    Layout.preferredHeight: 200 / itemsPerColumnAndRow
                    Layout.maximumHeight: 200 / itemsPerColumnAndRow
                    Layout.minimumHeight: 200 / itemsPerColumnAndRow
                    spacing: 0
                    Text {
                        text: qsTr(" ")
                        color: '#00aaaaaa'
                        font.pixelSize: 10 / itemsPerColumnAndRow
                        horizontalAlignment: Text.AlignHCenter
                    }

                    Text {
                        text: qsTr("当前重量")
                        color: "#AAAAAA"
                        font.pixelSize: 30 / itemsPerColumnAndRow
                        horizontalAlignment: Text.AlignHCenter
                    }

                    Text {
                        text: siloData.weight.toFixed(1) + "T"
                        color: "white"
                        font.pixelSize: 90 / itemsPerColumnAndRow
                        font.bold: true
                        horizontalAlignment: Text.AlignHCenter
                    }
                }
                // 总容量
                Text {
                    text: qsTr("总容量：") + siloData.capacity.toFixed(0) + "T"
                    color: "#AAAAAA"
                    font.pixelSize: 30 / itemsPerColumnAndRow
                    horizontalAlignment: Text.AlignHCenter
                }
                RowLayout {
                    Layout.row: 2  // 放置在第2行
                    Layout.column: 1  // 放置在第1列
                    Layout.columnSpan: 1  // 跨越1列
                    Layout.alignment: Qt.AlignRight  // 水平右对齐
                    // 无数据警告
                    Text {
                        text: siloData.isNoData ? qsTr("无数据") : ""
                        color: "#FF4444"
                        font.pixelSize: 30 / itemsPerColumnAndRow
                        font.bold: true
                        // 警告闪烁
                        SequentialAnimation on opacity {
                            id: warningBlinkAnimation2
                            running: siloData.isNoData
                            loops: Animation.Infinite
                            NumberAnimation { to: 0.3; duration: 500 }
                            NumberAnimation { to: 1; duration: 500 }
                        }
                    }
                
                    // 低料位警告
                    Text {
                        text: siloData.isLowLevel ? qsTr("低料位") : ""
                        color: "#FF4444"
                        font.pixelSize: 30 / itemsPerColumnAndRow
                        font.bold: true 
                        // 警告闪烁
                        SequentialAnimation on opacity {
                            id: warningBlinkAnimation
                            running: siloData.isLowLevel
                            loops: Animation.Infinite
                            NumberAnimation { to: 0.3; duration: 500 }
                            NumberAnimation { to: 1; duration: 500 }
                        }
                    }
                }
            }
        }
    }
    Dialog {
        anchors.centerIn: parent
        id: upgradeSaveOKDialog
        standardButtons: Dialog.Ok
        modal: true
        closePolicy: "CloseOnEscape"
        z:999
    }
    DateTimeDialog{
        id: settimedlg
        text: qsTr("设定日期时间")
        //type: "Time"
        onAccepted: {
            mymodbus.correctTime(getText("yyyy-MM-dd hh:mm:ss"));
        }
        onRejected: {
        }
    }
}
